<?php

namespace Apps\Manage\Controllers;


use Apps\Common\Libs\UserCommon;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use Apps\Common\Models\UserBase;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\UserAttribute;
use Apps\Common\Models\UserFollow;
use PhalconPlus\Api\Models\ApiUserAuth;

/**
 * 用户信息管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class UserController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('user');
    }

    public function indexAction()
    {
        $this->response->redirect('user/list');
    }

    /**
     * 用户列表
     */
    public function listAction() 
    {
    	$req = $this->request;
    	$type=$req->getQuery('type',null,'');//正常用户还是马甲用户
    	if($type==1){
        	$this->setLeftNav('user_list');
    	}else{
    		$this->setLeftNav('list');
    	}
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);

        $columns = [
            'user_id',
            'user_account',
            'user_nickname',
            'user_cover',
            'user_gender',
            'user_expert',
            'user_birthday',
            'user_realname',
            'user_district',
            'FULL_NAME district',
            'user_state',
            'user_addtime',
        	'persional_sign',
        	'is_manage'	
        ];
        $filterName = $req->getQuery('filterName', null, '');
        $reg_time=$req->getQuery('regTime',null,'');
        $filterMobile = $req->getQuery('filterMobile', null, '');
        $filterState = intval($req->getQuery('filterState', null, -10000));
        $filterGender = intval($req->getQuery('filterGender', null, -10000));
        $filterExpert = intval($req->getQuery('filterExpert', null, -10000));

        $filterProvince = $req->getQuery('filterProvince', null, '');
        $filterCity = $req->getQuery('filterCity', null, '');
        $filterDistrict = intval($req->getQuery('filterDistrict', null, -10000));

        $where = [];
        $bind = [];
        //筛选数据
		if($type!=''){
			$where[]='is_manage = :type:';
			$bind['type'] =$type;
		}
        if(!!$reg_time) {
        	$reg_timearr[]=explode("至",$reg_time);
        	$start_time=trim($reg_timearr[0][0]);
        	$end_time=trim($reg_timearr[0][1]);
        	$where[]="user_addtime >= :start_time:";
        	$where[]="user_addtime <= :end_time:";
        	$bind['start_time'] =$start_time;
        	$bind['end_time'] =$end_time;
        }
        if(!!$filterName) {
        	$where[] = 'user_nickname LIKE :fname:';
        	$bind['fname'] = '%' . $filterName . '%';
        }
        if(!!$filterMobile) {
            $where[] = 'user_account like :mobile:';
            $bind['mobile'] = "%".$filterMobile.'%';
        }

        if($filterState > -10000) {
            $where[] = 'user_state = :state:';
            $bind['state'] = $filterState;
        }

        if($filterGender > -10000) {
            $where[] = 'user_gender = :gender:';
            $bind['gender'] = $filterGender;
        }

        if($filterExpert > -10000) {
            $where[] = 'user_expert = :expert:';
            $bind['expert'] = $filterExpert;
        }

        // 地区
        $districts = [];
        if($filterDistrict > -10000) {
            $where[] = 'user_district = :district:';
            $bind['district'] = $filterDistrict;
        } elseif(!empty($filterCity)) {
            // 获取所有城市的下级区县值
            $dids = SysAreaZipDistrictPhonecode::query()
                ->columns(['K_ID id'])
                ->where('P_NM = :province: AND C_NM = :city:', ['province' => $filterProvince, 'city' => $filterCity])
                ->execute();
            foreach($dids as $d) {
                $districts[] = $d->id;
            }
        } elseif(!empty($filterProvince)) {
            // 获取所有城市的下级区县值
            $dids = SysAreaZipDistrictPhonecode::query()
                ->columns(['K_ID id'])
                ->where('P_NM = :p:', ['p' => $filterProvince])
                ->execute();
            foreach($dids as $d) {
                $districts[] = $d->id;
            }
        }

        if(count($districts) > 0) {
            $where[] = 'user_district IN(' . implode(', ', $districts) . ')';
        }

        $whereStr = count($where) > 0 ? implode(' AND ', $where) : '';
        $query = UserBase::query()
            ->columns($columns)
            ->leftJoin('Apps\Common\Models\SysAreaZipDistrictPhonecode', 'K_ID=user_district', 'area');

        if(count($where) > 0) {
            $query = $query->where($whereStr);
        }
        if(count($bind) > 0) {
            $query = $query->bind($bind);
        }

        $data = $query->orderBy('user_id DESC')
            ->limit($limit, $offset)
            ->execute();

        //总数
        $total = UserBase::count([
            'conditions' => $whereStr,
            'bind' => $bind
        ]);

        $this->view->setVars([
            'filterName' => $filterName,
            'filterMobile' => $filterMobile,
            'filterState' => $filterState,
            'filterGender' => $filterGender,
            'filterExpert' => $filterExpert,
            'filterProvince' => $filterProvince,
            'filterCity' => $filterCity,
            'filterDistrict' => $filterDistrict,
        	'regTime' => $reg_time,
        	'type' => $type
        ]);

        $this->view->setVars([
            'page' => $page,
            'limit' => $limit,
            'total' => $total
        ]);
        $this->view->setVar('type',$type);
        $this->view->setVar('data', $data);
        
    }

    /**
     * 设置用户状态
     * @return $this|ResponseResult
     */
    public function setStateAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, -10000));
            if(!in_array($state, [-1, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = UserBase::findFirst('user_id=' . $id);
            if($info) {
                $info->update(['user_state' => $state]);
            }
            $tokenModel = ApiUserAuth::findFirst('user_id=' . $id);
            if($tokenModel){
                $info->update(['state' => 0]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 设置专家
     * @return $this|ResponseResult
     */
    public function setExpertAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $expert = intval($req->getPost('expert', null, -10000));
            if(!in_array($expert, [0, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = UserBase::findFirst('user_id=' . $id);
            if($info) {
                $info->update(['user_expert' => $expert]);
                if($expert==0){
                	$userAttr=UserAttribute::findFirst('user_id ='.$id .' and attr_type = 103 and attr_state = 1');
                	if($userAttr){
                		$userAttr->delete();
                	}
                }
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 修改密码
     * @return $this|ResponseResult
     */
    public function setPasswdAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $pwd = $req->getPost('pwd');
            if(empty($pwd)) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = UserBase::findFirst('user_id=' . $id);
            if($info) {
                $info->update(['user_password' => UserCommon::hashPassword($pwd, $this->di)]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }
    /**
     * 添加马甲用户
     * @date: 2016-1-4 
     * @author: futao
     */
    public function addAction(){
    	$this->setLeftNav('add');
    	
    }
    /**
     * 保存马甲用户信息
     * @date: 2016-1-4 
     * @author: futao
     */
    public function addsaveAction(){
    	$req = $this->request;
    	$account=$req->getPost('account',null,'');
    	$district=$req->getPost('district',null,'');
    	$password=$req->getPost('password',null,'');
    	$nickname=$req->getPost('nickname',null,'');
    	$realname=$req->getPost('realname',null,'');
    	$phone=$req->getPost('phone',null,'');
    	$persional_sign=$req->getPost('persional_sign',null,'');
    	$birthday=$req->getPost('birthday',null,'');
    	$gender = $req->getPost('sex' ,null,2);
    	$echo = function($msg, $state=false){
    		echo '<script type="text/javascript">';
    		echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')';
    		echo '</script>';
    	};
    	$userinfo=UserBase::findFirst("user_account=$account");
    	if($userinfo){
    		$echo('账号已被注册!');
    		return ;
    	}
    	
    	$uploadFile = new UploadPic();
    	$uploadFile->request = $req;
    	$cover = $uploadFile->userCover();
    	if($cover == false) {
    		if($_FILES['avatar']['error'] == 1) {
    			$echo('封面大小超过了2M！');
    		} else {
    			$echo('封面必须上传！');
    		}
    		return;
    	}
    	$usermodel=new UserBase();
    	//个性签名编码
    	if($persional_sign!=''){
    		$usermodel->persional_sign=base64_encode(serialize($persional_sign));
    	}
    	$usermodel->user_account=$account;
    	$usermodel->user_password=UserCommon::hashPassword($password, $this->di);
    	$usermodel->user_district=$district;
    	$usermodel->user_nickname=$nickname;
    	$usermodel->user_realname=$realname;
    	$usermodel->bind_phone=$phone;
    	//$usermodel->persional_sign=$persional_sign;
    	$usermodel->user_birthday=$birthday;
    	$usermodel->user_cover=$cover;
    	$usermodel->is_manage=1;
    	$usermodel->user_gender=$gender;
    	if($usermodel->save()){
    		$echo('ok',true);
    	}else{
    		$echo("添加失败！");
    	}
    }
    /**
     * 编辑用户信息
     * @date: 2016-1-5 
     * @author: futao
     */
    public function editAction(){
    	$this->setLeftNav("update");
    	$req=$this->request;
    	$id=$req->getQuery("id",null,0);
    	$action=$req->getQuery("action",null,'');
    	$info=UserBase::query()
    	->columns([
			'user_account',
			'user_password',
			'user_district',
			'user_nickname',
			'user_realname',
			'bind_phone',
			'persional_sign',
			'user_birthday',
			'user_cover',
    		'user_gender',
    		'user_expert',
            'expert_follow_count'
    	])
    	->where("user_id = :id:")
    	->bind(['id'=>$id])
    	->execute()->getFirst();
    	if(!$info){
    		$this->view->disable();
    		echo '用户不存在！';
    		return;
    	}
    	if($info->user_expert==1){
    		$userAttr=UserAttribute::findFirst('user_id ='.$id .' and attr_type = 103 and attr_state = 1');
    		$this->view->setVar('user_attr',json_decode($userAttr->attr_value_json));
    	}
    	//个性签名解码
    	if(unserialize(base64_decode($info->persional_sign))){
    		$info->persional_sign=unserialize(base64_decode($info->persional_sign));
    	}
    	$info->user_cover=PicUrl::UserCover($info->user_cover,$this->di);
    	$userArea=SysAreaZipDistrictPhonecode::findFirst("K_ID = ".$info->user_district);
    	$tagList=BeautyParlorTagInfo::find("tag_state = 1 and parent_id !=0");
    	$this->view->setVar('taglist',$tagList);
    	$this->view->setVar('userArea', $userArea);
    	$this->view->setVar('userInfo', $info);	
    	$this->view->setVar('userId',$id);
    	$this->view->setVar('action',$action);
    }
    /**
     * 更新用户信息
     * @date: 2016-1-5 
     * @author: futao
     */
    public function editsaveAction(){
    	$req = $this->request;
    	$district=$req->getPost('district',null,'');
    	$nickname=$req->getPost('nickname',null,'');
    	$realname=$req->getPost('realname',null,'');
    	$phone=$req->getPost('phone',null,'');
    	$persional_sign=$req->getPost('persional_sign',null,'');
    	$birthday=$req->getPost('birthday',null,'');
    	$userId=intval($req->getPost('user_id',null,0));
    	$gender = $req->getPost('sex' ,null,2);
    	$experience=$req->getPost("experience",null,'');//从业经验
    	$field=$req->getPost("field",null,'');//擅长领域
    	$experttitle=$req->getPost("experttitle",null,'');//专家头衔
        $followCount = $req->getPost('expert_follow_count' ,null,0);
    	$echo = function($msg, $state=false){
    		echo '<script type="text/javascript">';
    		echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')'; 
    		echo '</script>';
    	};
    	$usermodel=UserBase::findFirst("user_id = $userId and is_manage = 1");
    	if(!$usermodel){
    		$echo ("用户不存在！");
    		return;
    	}
        $info=UserAttribute::findFirst("user_id = $userId and attr_type = 103");
        if($info){
            if($field=="" || !is_array($field)){
                $echo ("擅长领域必填！");
                return;
            }
            $data=[
                'experience'=>$experience,
                'experttitle'=>$experttitle,
                'field'=>$field
            ];
            $datajson=json_encode($data);
            $info->attr_value_json = $datajson;
            $info->save();
        }
    	//用户头像
    	if($_FILES['avatar']['name']!=''){
	    	$uploadFile = new UploadPic();
	    	$uploadFile->request = $req;
	    	$cover = $uploadFile->userCover();
	    	if($cover == false) {
	    		if($_FILES['avatar']['error'] == 1) {
	    			$echo('封面大小超过了2M！');
	    		} else {
	    			$echo('封面必须上传！');
	    		}
	    		return;
	    	}
	    	$usermodel->user_cover=$cover;
    	}
    	$usermodel->user_district=$district;
    	$usermodel->user_nickname=$nickname;
    	$usermodel->user_realname=$realname;
    	$usermodel->bind_phone=$phone;
        $usermodel->expert_follow_count=$followCount;
    	//个性签名编码
    	if($persional_sign!=''){
    		$usermodel->persional_sign = base64_encode(serialize($persional_sign));
    	}else{
            $usermodel->persional_sign = "";
        }
    	//$usermodel->persional_sign=$persional_sign;
    	$usermodel->user_birthday=$birthday;
    	$usermodel->user_gender = $gender;
    	if($usermodel->save()){
    		$echo('ok',true);
    	}else{
    		$echo("添加失败！");
    	}
    } 
    /**
     * 设置成专家信息
     * @date: 2016-1-6 
     * @author: futao
     */
    public function setExpertinfoAction(){
    	$req=$this->request;
    	if(!$req->isPost()){
	    	$userId=$req->getQuery('userid',null,0);
	    	if(!$userId){
	    		echo "用户不存在";
	    		return;
	    	}
	    	$tagList=BeautyParlorTagInfo::find("tag_state = 1 and parent_id !=0");
            $UserFollow = new UserFollow();
            $count = $UserFollow->getToFollowCount($userId);
            $this->view->setVar("count",$count);
	    	$this->view->setVar("userId",$userId);
	    	$this->view->setVar("tagList",$tagList);
	    	$this -> view -> pick('user/setexpertinfo');
	    	return;
    	}
    	$response = new ResponseResult();
    	$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
    	$response->callbackJavascriptTag = true;
    	
    	//$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数问题！');
    	/* $response->sendResult(1);
    	return $response; */
    	$experience=$req->getPost("experience",null,'');//从业经验
    	$userId=$req->getPost("userId",null,'');
    	$field=$req->getPost("field",null,'');//擅长领域
    	$experttitle=$req->getPost("experttitle",null,'');//专家头衔
    	//验证数据
    	if($field=="" || !is_array($field)){
    		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '擅长领域必填！');
    		return $response;
    	}
    	if($userId==""){
    		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数错误！');
    		return $response;
    	}
    	$userInfo=UserBase::findFirst($userId);
    	if(!$userInfo){
    		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数错误！');
    		return $response;
    	}
    	$data=[
			'experience'=>$experience,
			'experttitle'=>$experttitle,
			'field'=>$field
    	];
    	$datajson=json_encode($data);
    	$userAttr=new UserAttribute();
    	$userAttr->attr_value_json=$datajson;
    	$userAttr->user_id=$userId;
    	$userAttr->attr_type=103;
    	$userAttr->attr_state=1;
    	$userAttr->attr_key=time();
    	$userAttrId=$userAttr->save();
    	if(!$userAttrId){
    		$response->sendError(ResponseResultStatus::ERROR, '设置失败！');
    		return $response;
    	}
        $userInfo->expert_follow_count = $req->getPost("fans",null,0);
    	$userInfo->user_expert=1;
    	if($userInfo->save()){
    		$response->sendResult(1);
    	}else{
    		$response->sendError(ResponseResultStatus::ERROR, '设置失败！');
    	}
    	return $response;
    }   
}